<template>
  <el-container>
    <el-header style="height: 40px;">
      <el-button type="primary" @click="saveRoles">保存</el-button>
    </el-header>
    <el-main>
      <el-tree
        :data="data2"
        v-loading="loading"
        show-checkbox
        node-key="funcid"
        ref="tree"
        :highlight-current="true"
        :default-expanded-keys="checks"
        :default-checked-keys="checks"
        :props="defaultProps">
      </el-tree>
    </el-main>
  </el-container>
</template>

<script>
  import { selRolesByName, editRolesByName } from '../../../api/system/functionRoles'

  export default {
    name: 'functionRolesTrees',
    props: ['treeData'],
    data() {
      return {
        data2: [],
        maxOrgNo: '',
        rolesId: '',
        checks: [],
        defaultProps: {
          children: 'children',
          label: 'funcname'
        },
        loading: false
      }
    },
    watch: {
      treeData: function(val) {
        const $this = this
        $this.loading = true
        this.rolesId = val.roleid
        selRolesByName(this.rolesId).then(res => {
          $this.checks.splice(0, $this.checks.length)
          const isCheck = res.children
          const isCheckLen = isCheck.length
          for (var i = 0; i < isCheckLen; i++) {
            for (var x = 0; x < isCheck[i].children.length; x++) {
              if (isCheck[i].children[x].children === null || isCheck[i].children[x].children === '') {
                if (isCheck[i].children[x].checked) {
                  $this.checks.push(isCheck[i].children[x].funcid)
                }
              } else {
                for (var j = 0; j < isCheck[i].children[x].children.length; j++) {
                  if (isCheck[i].children[x].children[j].checked) {
                    $this.checks.push(isCheck[i].children[x].children[j].funcid)
                  }
                }
              }
            }
          }
          $this.maxOrgNo = res.children[0].funcid
          $this.loading = false
          $this.data2 = res.children
        })
      }
    },
    methods: {
      saveRoles: function() {
        this.loading = true
        const $this = this
        let childList = $this.$refs.tree.getCheckedKeys()
        let parentList = $this.$refs.tree.getHalfCheckedKeys()
        childList.push.apply(childList, parentList)
        editRolesByName($this.rolesId, childList).then(res => {
          this.loading = false
          $this.$message({
            message: '修改成功',
            type: 'success'
          })
        })
      }
    }
  }
</script>

<style scoped>
  .el-header{
    text-align: right;
    padding: 8px 0px;
    height:20px;
    margin: 0;
    background-color:#9FABC4;
  }
  .el-header .el-button{
    width: 80px;
    height: 24px;
    font-family: MicrosoftYaHei;
    font-size:12px;
    padding: 4px 20px;
  }
</style>
